﻿#include "SDLRenderRGBWindow.h"
#include <QFile>
#include <QFileDialog>
#include <QDebug>
#include "utils/SDLRenderUtil.h"
#include <thread>

SDLRenderRGBWindow::SDLRenderRGBWindow(QWidget* parent)
	: QWidget(parent)
{
	ui.setupUi(this);
	this->setWindowTitle("SDL播放RGB文件");
	//this->setFixedSize(QSize(400, 480));
	setAttribute(Qt::WA_DeleteOnClose, true);  // 关闭时自动销毁窗口

}

void SDLRenderRGBWindow::choiceRGB24File()
{
	mWidth = ui.labelVideo->width();
	mHeight = ui.labelVideo->height();
	QString filter = "RGB 文件 (*.*);;所有文件 (*.*)";
	// 打开文件选择对话框，选择单个文件
	QString filePath = QFileDialog::getOpenFileName(this, "选择 RGB 文件", "", filter);
	BinaryFileReader::Get()->filename = filePath.toStdString();
	BinaryFileReader::Get()->width = mWidth;
	BinaryFileReader::Get()->height = mHeight;
	BinaryFileReader::Get()->Init();

	SDLRenderUtil::Get()->width = mWidth;
	SDLRenderUtil::Get()->height = mHeight;
	SDLRenderUtil::Get()->winId = (void*)ui.labelVideo->winId();
	SDLRenderUtil::Get()->PIX_FMT = 2;
	SDLRenderUtil::Get()->Init();

	// 创建并启动后台线程
	renderThread = std::make_unique<std::thread>(&SDLRenderRGBWindow::RenderVideo, this);

	//std::thread renderThread([=] {
	//	char* data = new  char[mWidth * mHeight * 3];
	//	for (;;) {
	//		SDLRenderUtil::Get()->isEventQuit();
	//		bool ret = BinaryFileReader::Get()->ReadRGB24(data);
	//		if (!ret) {
	//			break;
	//		}
	//		SDLRenderUtil::Get()->Render(data);
	//		std::this_thread::sleep_for(33ms);
	//	}
	//	delete data;
	//	});
	//renderThread.detach();//线程分离
	//renderThread.join();//等待子线程结束
}

void SDLRenderRGBWindow::RenderVideo()
{
	char* data = new  char[mWidth * mHeight * 3];
	for (;;) {
		if (!isRunning)break;
		SDLRenderUtil::Get()->isEventQuit();
		bool ret = BinaryFileReader::Get()->ReadRGB24(data);
		if (!ret) {
			break;
		}
		SDLRenderUtil::Get()->Render(data);
		std::this_thread::sleep_for(33ms);
	}
	if (data) {
		delete data;
	}
	qDebug() << "已释放了data内存";
}

void SDLRenderRGBWindow::closeEvent(QCloseEvent* event) {
	isRunning = false;
	// 等待线程结束
	if (renderThread && renderThread->joinable()) {
		renderThread->join();
	}
	BinaryFileReader::Get()->Close();
	SDLRenderUtil::Get()->Close();
	event->accept();  // 接受关闭事件（允许关闭）
	qDebug() << "窗口已关闭";
}
SDLRenderRGBWindow::~SDLRenderRGBWindow()
{
	qDebug() << "执行了SDLRenderRGBWindow的析构函数";
}
